<template>
	<BaseField v-bind="props" :visible="visible">
		<!-- 单选多选 -->
		<div class="field-text" style="width: 100%">
			<div class="" v-if="status === 'view'" style="display: flex; flex-wrap: wrap; gap: 4px">
				<template v-if="getChooseArr?.length">
					<ComTag class="tag" v-for="item in getChooseArr" :key="item.id" :color="item.style"> {{ item.parm }} </ComTag>
				</template>
				<template v-else> -- </template>
			</div>
			<div class="edit" id="selectEdit" style="width: 100%" v-else>
				<a-select
				:size="size"
					style="width: 100%"
					v-model="dataValue"
					allow-clear
					allow-search
					:multiple="fieldType === 'multiSelect'"
					:placeholder="$t('base.placeholderSelect')"
					@change="handleUpdateChange(true)"
					@popup-visible-change="visibleChange"
					@remove="visibleChange(false)"
					@clear="visibleChange(false)"
				>
					<a-option v-for="item in options" :value="item.id">{{ item.parm }}</a-option>
				</a-select>
			</div>
		</div>
	</BaseField>
</template>

<script setup lang="ts">
import { propsInfo } from "./utils/props";
const { wsCache } = useCache();

const props = defineProps({
	...propsInfo,
	options: {
		type: Array,
		default: () => []
	}
});
const emit = defineEmits(["update:modelValue", "update:fieldShow", "change"]);

const dataValue: any = ref([]);
const visible = ref(false);
const visibleChange = (bool) => {
	visible.value = bool;
	wsCache.set("visible", bool);
	if (!bool && changeFlag.value) {
		emit("change", dataValue.value);
		changeFlag.value = false;
	}
};

const changeFlag = ref(false);
const handleUpdateChange = () => {
	changeFlag.value = true;
	handleChange();
};
const handleChange = () => {
	const str = getChooseArr.value.map((i) => i.parm).join(",");
	if (props.fieldType !== "multiSelect") {
		emit("update:modelValue", dataValue.value);
	} else {
		emit("update:modelValue", dataValue.value.join(","));
	}
	emit("update:fieldShow", str);
};

const getChooseArr = computed(() => {
	if (props.prop?.addField) return props.modelValue; //添加字段的时候使用默认值
	if (!props.options) return [];
	if (props.fieldType !== "multiSelect") {
		return props.options.filter((item) => dataValue.value === item.id);
	} else {
		return props.options.filter((item) => dataValue.value.includes(item.id));
	}
});
watch(
	() => props.modelValue,
	(data) => {
		if (props.prop?.addField) return; //添加字段的时候使用默认值
		if (data) {
			if (props.fieldType !== "multiSelect") {
				dataValue.value = Number(data);
			} else {
				dataValue.value = data.split(",").map(Number);
			}
			handleChange();
		} else {
			dataValue.value = [];
		}
	},
	{ immediate: true }
);
</script>

<style scoped></style>
